/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi
 
    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/
var anno_state; // states correspond directly to css classes for top-level annotation UI functions
var anno_saving = false;
var anno_curid = "";
var anno_hover;
var anno_hover_author;
var anno_hover_summary;
var anno_notes=[];
var anno_elem=[];
var anno_helem=[];

// process user events to change annotation UI state
function annoAction(event) {
    switch(anno_state) {
    case 'create-anno':
	changeAnno('new-anno');
	break;
    case 'new-anno':
	changeAnno('create-anno');
	break;
    case 'edit-anno':
	break;
    case 'disp-anno':
	toggleAnno();
	break;
    case 'create-quick':
	//	changeAnno('new-quick');
	break;
    case 'new-quick':
	changeAnno('create-quick');
	break;
    case 'edit-quick':
	break;
    case 'disp-quick':
	break;
    case 'list-quick':
	break;
    }
}

// show/hide UI elements
function changeAnno(state) {
    anno_state = state;
    $('.annotation-heading, .annotation-body').hide();

    switch (state) {
    case 'new-anno':
	$('#anno-head-new-anno').show();
	$('#anno-body-edit-anno').show();
	break;
    case 'edit-anno':
	$('#anno-head-edit-anno').show();
	$('#anno-body-edit-anno').show();
	break;
    default:
	$('#anno-head-'+state+',#anno-body-'+state).show();
    }


}

function setToAnnotateMode() {
    switch (anno_state) {
    case 'create-quick':
    default:
	changeAnno('create-anno');
	break;
    case 'edit-quick':
    case 'list-quick':
    case 'disp-quick':
	changeAnno('edit-anno');
	break;
    case 'edit-anno':
	break; // do nothing
    }
}

function setToQuickNoteMode() {
    switch (anno_state) {
    case 'create-anno':
	changeAnno('create-quick');
	break;
    case 'edit-anno':
	changeAnno('edit-quick');
	break;
    }
}

var ato;
function check_annotate_logged_in() {
    if (anno_login) {
	window.clearInterval(ato);
	var tbr = $('#annotation-toolbar');
	if (tbr) {
	    tbr.show();
	}
    }
}

function checkSelect(event) {
    var hil = getHighlight();
    last_selected_text = hil;
    if (hil == false) {
	//	setToQuickNoteMode();
	return;
    }
    var hil_trunc = hil.substring(0,65);
    $('#anno-text-snip-1,#anno-text-snip-2').text(hil_trunc);
}
function getHighlight()
{
    var t = '';
    if (window.getSelection)
	t = window.getSelection();
    else if (document.getSelection)
	t = document.getSelection();
    else if (document.selection)
	t = document.selection.createRange().text;
    if (t != '') {
	return t.toString();
    }
    else
	return false;
}

function showAnno(noteid) {
    var note;
    if (!(note = anno_notes[noteid]))
	return;
    
    var is_annotator = (note.signed == _anno_user_sig);

    var edl = $('#anno-edit-link,#anno-delete-link');
    if (_anno_isowner || is_annotator) {
	edl.show();
    }
    else {
	edl.hide();
    }

    $('#anno-author').text(note.signed);
    var adiv = $('#anno-disp-wrapper');
    adiv.html(anno_elem[noteid]);
    $('#anno-body-disp-anno').children().show();
    changeAnno('disp-anno');
}

function toggleAnno() {
    var j = $('.annotation-body');
    if (j.is(':visible'))
	j.hide();
    else
	openAnno();
}
function closeAnno() {
    $('.annotation-body').hide();
}
function openAnno() {
    $('#anno-body-'+anno_state).show();
}

function targetClick() {
    anno_curid = $(this).attr("fcnote_id");
    $(".annotation").hide();
    showAnno(anno_curid);
}

function targetMouseOver() {
    var noteid = $(this).attr("fcnote_id");
    $('#hover-author').text(anno_notes[noteid].signed);
    $('#hover-summary').html(anno_helem[noteid]);
    anno_hover.css({left: "auto"});
    $(this).append(anno_hover);
    anno_hover.show();
}
function targetMouseOut() {
    var noteid = $(this).attr("fcnote_id");
    anno_hover.hide();
}

$(document).ready(function(){
	$('.notes').mouseup(checkSelect);
	$('.annotation-heading').click(annoAction);
	changeAnno('create-quick');
	anno_hover = $('#anno-hover');
	anno_hover_author = $('#hover-author');
	anno_hover_summary = $('#hover-summary');
    });

function annotate_note_editor(p) {
	var me = this;
	
	var peer = p;

	//	var noteTextarea = document.getElementById("note_textarea");
	//	var saveButton = document.getElementById("save_button");
	//	var cancelButton = document.getElementById("cancel_button");
	//      var urlInput = document.getElementById("note_link_to");
	//	var urlTitle = document.getElementById("note_link_title");
	//	var tagsInput = document.getElementById("tags_input");
	//	noteTextarea.style.backgroundColor = "#d0d0d0";
	
	$('.btn_save').click(saveNote);
	
	//	saveButton.onclick = saveNote;
	//	cancelButton.onclick = cancelNote;
	
	 
	//	var livenote = false;
	
	
	me.editNew = function() {
	    //	    var n = {"notetext":"", "tags":"", "linkTo":"", "linkTitle":""};
	    //	    livenote = true;
	    changeAnno('create-anno');
	    //		me.edit(n);
	}
	
	
	me.edit = function(note) {
	    var fcki = FCKeditorAPI.GetInstance('FCKAnnoEdit');
	    fcki.SetHTML(note.notetext);
	    //	    livenote = true;
	    changeAnno('edit-anno');
	/*
		tagsInput.value = note.tags;
		urlInput.value = note.linkTo;
		urlTitle.value = note.linkTitle;
		noteTextarea.style.backgroundColor = "#ffffff";
	    */
	}
	
	function saveNote() {
	    var fcki = FCKeditorAPI.GetInstance('FCKAnnoEdit');
	    //	    if (livenote) {
		anno_saving = true;
		var n = {};
		n.notetext = fcki.GetHTML();
		fcki.SetHTML("");
		closeAnno();
		changeAnno('create-quick');
		//			n.linkTo = urlInput.value;
		//n.linkTitle = urlTitle.value;
		//n.tags = tagsInput.value;
		//clearTextarea();
		//n.color = "#ff8080";
		peer.saveAndShow(n);
		//	    }
	} 
	
	function cancelNote() {
		clearTextarea();
		peer.cancelNote();
	}
	
	function clearTextarea() {
		noteTextarea.value = "";
		urlInput.value = "";
		urlTitle.value = "";
		tagsInput.value = "";
		//		livenote = false;
		noteTextarea.style.backgroundColor = "#d0d0d0";
	}
}

function annotate_note_display(p) {
	var me = this;
	var peer = p;


	var divs = [];
	var divsById = {};
	
	function empty(elt) {
	    while (elt && elt.hasChildNodes()) {
	         elt.removeChild(elt.lastChild);
	    }
	}
	function noteClicked(e) { 
	}
	me.removeAllNotes = function() { }
	me.gotFinalID = function(oldid, newid) {
	    //		divsById[newid] = divsById[oldid];
	    //		divsById[newid].noteid = newid;
	}

	me.addNote = function(note) {
	    anno_notes[note.id]=note;
	    var nt = '<div>'+note.notetext+'</div>';
	    anno_elem[note.id] = $(nt);
	    anno_helem[note.id] = $(nt);
	}
	me.removeNote = function(note) {
	    anno_hover.remove();
	    delete anno_notes[note.id];
	    anno_elem[note.id].remove();
	    anno_helem[note.id].remove();
	    delete anno_elem[note.id];
	    delete anno_helem[note.id];
	}
	me.highlightNote = function(noteid) {}
	me.updateNote = function(note) {
	    this.addNote(note);

	    var ids = peer.getHighlightIds(note.id);
	    var sel = "";
	    for (var i=0; i < ids.length; i++) {
		if (i > 0)
		    sel += ",";
		sel += "#" + ids[i];
	    }
	    $(sel).unbind();
	    $(sel).attr("fcnote_id",note.id);
	    $(sel).click(targetClick);
	    $(sel).hover(targetMouseOver,targetMouseOut);
	}

	function editActive() {
		if (anno_curid != "") {
		    activeid = anno_curid;
		    peer.editNote(anno_curid);
		}
	}
	
	function deleteActive() {
	    if (confirm("Do you wish to delete this annotation?\nClick 'OK' to delete.")) {
		changeAnno('create-quick');
		if (anno_curid != "") {
     		    activeid = anno_curid;
		    peer.deleteNote(anno_curid);
		}
	    }
	}

	var activeid = "";
	$('#anno-edit-link').click(editActive);
	$('#anno-delete-link').click(deleteActive);

	/*	
	var ebut = document.getElementById("edit_button");
	var rbut = document.getElementById("reply_button");
	var dbut = document.getElementById("delete_button");
	ebut.onmousedown = editActive;
	rbut.onmousedown = replyActive;
	dbut.onmousedown = deleteActive;
	
	var activeid = "";
	
	me.updateNote = function(note) {
		var div = divsById[note.id];
		empty(div);
		if (note.linkTo) {
			var a = document.createElement("a");
			a.innerHTML = note.linkTitle;
			a.href = note.linkTo;
			var da = document.createElement("div");
			da.appendChild(a);
			div.appendChild(da);
		}
		if (note.tags) {
			var tspan = document.createElement("div");
			tspan.innerHTML = note.tags;
			tspan.className = "noteTags";
			div.appendChild(tspan);
		}
		
		var spn = document.createElement("span");
		spn.innerHTML = note.notetext;
		div.appendChild(spn);
		var att = document.createElement("div");
		div.appendChild(att);
		att.className = "noteMeta"
		att.innerHTML =   note.author + " " + note.date;
	
		if (note.replies) {
			for (var i = 0; i < note.replies.length; i++) {
				var r = note.replies[i];
				var rdiv = document.createElement("div");
				rdiv.className = "reply";
				rdiv.innerHTML = r.author +", " + r.date + ": " + r.notetext;
				div.appendChild(rdiv);
			}
		}
	}
	
	function empty(elt) {
	    while (elt && elt.hasChildNodes()) {
	         elt.removeChild(elt.lastChild);
	    }
	}
	
	function HoverActions(n) {
		var note = n;
	 	
		this.entered = function() {
			var msgdiv = document.getElementById("message_area");
			empty(msgdiv);
			var p = document.createElement("p");
			p.innerHTML = "Highlight action example showing the text of " +
					"the last note the mouse visited:<br/><b> " + n.notetext + "</b>";
			//			msgdiv.appendChild(p);
		}
	}
		
		
	function noteClicked(e) {
		activeid = "";
		var dv = getTarget(e);
		if (dv.noteid) {
			activeid = dv.noteid;
		} else {
			var wk = dv.parentNode;
			while (wk) {
				if (wk.noteid) {
					activeid = wk.noteid;
					break;
				}  
				wk = wk.parentNode;
			}
		}
		if (activeid != "") {
			peer.highlightNote(activeid);
		}
	}
	
	function editActive() {
		if (activeid != "") {
			peer.editNote(activeid);
		}
	}
	
	
	function replyActive() {
		if (activeid != "") {
			peer.replyToNote(activeid);
		}
	}
	
	
	
	function deleteActive() {
		if (activeid != "") {
			peer.deleteNote(activeid);
			divsById[activeid].style.display = "none";
		}
	}
	
	
	
	function getTarget(x) {
	    x = (x || window.event);
	    return (x.target || x.srcElement);
    }
	*/
}


